<?php
namespace App\Lib\Base;

use Yaf\Bootstrap_Abstract;
use Yaf\Application;
use Yaf\Registry;
use Yaf\Dispatcher;


use Illuminate\View\Engines\EngineResolver;
use Illuminate\View\Engines\PhpEngine;
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Engines\CompilerEngine;

class BaseBootstrap extends Bootstrap_Abstract
{
    /**
     * blade模板初始化
     * @param \Yaf\Dispatcher $dispatcher
     */
    public function _initView(Dispatcher $dispatcher){
        $modulesName = $dispatcher->getRequest()->module;
        $view_path = APP_PATH . '/app/modules/' . $modulesName . '/views';

        $finder = new \Illuminate\View\FileViewFinder(new \Illuminate\Filesystem\Filesystem(), [$view_path]);  //finder实例
        $view_factory = new \App\Lib\Tool\View($this->registerEngineResolver(), $finder, new \App\Lib\Tool\Dispatcher());  //视图工厂

        $dispatcher->setView($view_factory);  //设置模板引擎
    }

    /**
     * 注册模板引擎
     * @return EngineResolver
     */
    protected function registerEngineResolver()
    {
        $resolver = new EngineResolver;

        foreach (['php', 'blade'] as $engine) {
            $this->{'register'.ucfirst($engine).'Engine'}($resolver);
        }

        return $resolver;
    }

    /**
     * 注册php模板引擎
     * @param  \Illuminate\View\Engines\EngineResolver  $resolver
     * @return void
     */
    protected function registerPhpEngine($resolver)
    {
        $resolver->register('php', function () {
            return new PhpEngine;
        });
    }

    /**
     * 注册blade模板引擎
     * @param  \Illuminate\View\Engines\EngineResolver  $resolver
     * @return void
     */
    protected function registerBladeEngine($resolver)
    {
        $cache = Registry::get('config');  //获取编译路径
        $cache = $cache['application']['compile'];

        $bladeCompiler = new BladeCompiler(new \Illuminate\Filesystem\Filesystem(), $cache); //实例blade模板编译类

        $resolver->register('blade', function () use ($bladeCompiler) {
            return new CompilerEngine($bladeCompiler);
        });
    }
}